package com.ruoyi.admin.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.admin.domain.AlipayNameOrder;
import com.ruoyi.admin.service.IAlipayNameOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import java.io.BufferedReader;

/**
 * 姓名订单Controller
 * 
 * @author ouran
 * @date 2025-06-16
 */
@RestController
@RequestMapping("/admin/admin")
public class AlipayNameOrderController extends BaseController {
    @Autowired
    private IAlipayNameOrderService alipayNameOrderService;

    /**
     * 查询姓名订单列表
     */
    @PreAuthorize("@ss.hasPermi('admin:admin:list')")
    @GetMapping("/list")
    public TableDataInfo list(AlipayNameOrder alipayNameOrder) {
        startPage();
        List<AlipayNameOrder> list = alipayNameOrderService.selectAlipayNameOrderList(alipayNameOrder);
        return getDataTable(list);
    }

    /**
     * 导出姓名订单列表
     */
    @PreAuthorize("@ss.hasPermi('admin:admin:export')")
    @Log(title = "姓名订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AlipayNameOrder alipayNameOrder) {
        List<AlipayNameOrder> list = alipayNameOrderService.selectAlipayNameOrderList(alipayNameOrder);
        ExcelUtil<AlipayNameOrder> util = new ExcelUtil<AlipayNameOrder>(AlipayNameOrder.class);
        util.exportExcel(response, list, "姓名订单数据");
    }

    /**
     * 获取姓名订单详细信息
     */
    @PreAuthorize("@ss.hasPermi('admin:admin:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(alipayNameOrderService.selectAlipayNameOrderById(id));
    }

    /**
     * 新增姓名订单
     */
    @PreAuthorize("@ss.hasPermi('admin:admin:add')")
    @Log(title = "姓名订单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AlipayNameOrder alipayNameOrder) {
        return toAjax(alipayNameOrderService.insertAlipayNameOrder(alipayNameOrder));
    }

    /**
     * 修改姓名订单
     */
    @PreAuthorize("@ss.hasPermi('admin:admin:edit')")
    @Log(title = "姓名订单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AlipayNameOrder alipayNameOrder) {
        return toAjax(alipayNameOrderService.updateAlipayNameOrder(alipayNameOrder));
    }

    /**
     * 删除姓名订单
     */
    @PreAuthorize("@ss.hasPermi('admin:admin:remove')")
    @Log(title = "姓名订单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(alipayNameOrderService.deleteAlipayNameOrderByIds(ids));
    }

    /**
     * 手动生成姓名
     */
    @PostMapping("/pathMethodName")
    public Map<String, Object> createNameList(@RequestBody Map<String, Object> params) {
        // return alipayNameOrderService.createNameList();
        System.out.println("params：" + params);

        Map<String, Object> result = new HashMap<>(); // 初始化result对象
        // 调用起名接口
        Set<String> uniqueNames = new HashSet<>(); // 用于去重
        try {
            String key = "aGPUwVr4qIPEz16qqpKIMc6rHJ"; // 请替换为实际的接口密钥
            String surname = (String) params.get("surname");
            String sex = String.valueOf(params.get("sex"));
            // 处理日期参数
            String birthdayStr = (String) params.get("birthday");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date birthdayDate = sdf.parse(birthdayStr);
            String birthday = sdf.format(birthdayDate);

            String type = String.valueOf(params.get("type"));
            String quantity = "30";

            // 获取order对象（假设从参数中获取orderNo，然后查询得到order对象）
            String orderNo = (String) params.get("orderNo");
            // 这里需要根据实际情况获取order对象，例如通过service查询
            // AlipayNameOrder order = alipayNameOrderService.getOrderByOrderNo(orderNo);
            // 为了演示，暂时创建一个简单的order对象
            AlipayNameOrder order = new AlipayNameOrder();
            order.setOrderNo(orderNo);

            // 最多调用4次API（4×30=120），确保能获取足够不重复名字
            for (int i = 0; i < 4; i++) {
                // 添加随机参数避免API返回重复结果
                String url = "https://qqlykm.cn/api/qiming/index?"
                        + "key=" + URLEncoder.encode(key, "utf-8")
                        + "&surname=" + URLEncoder.encode(surname, "utf-8")
                        + "&sex=" + URLEncoder.encode(sex, "utf-8")
                        + "&birthday=" + URLEncoder.encode(birthday, "utf-8")
                        + "&type=" + URLEncoder.encode(type, "utf-8")
                        + "&quantity=" + URLEncoder.encode(quantity, "utf-8")
                        + "&random=" + System.currentTimeMillis(); // 添加随机参数

                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                try {
                    con.setRequestMethod("GET");
                    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

                    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
                    String inputLine;
                    StringBuilder response = new StringBuilder();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                    // 解析返回的 JSON 数据
                    JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                    JSONObject data = jsonResponse.getJSONObject("data");
                    JSONArray namesArray = data.getJSONArray("list");

                    // 直接添加到去重集合
                    for (int j = 0; j < namesArray.size(); j++) {
                        JSONObject nameObj = namesArray.getJSONObject(j);
                        String name = nameObj.getString("name");
                        uniqueNames.add(name); // 添加到Set实现去重
                        // 达到100个时停止
                        if (uniqueNames.size() >= 100) {
                            break;
                        }
                    }
                    if (uniqueNames.size() >= 100) {
                        break; // 达到数量提前终止循环
                    }
                } finally {
                    con.disconnect(); // 确保连接被关闭
                }
            }

            // 转换为List（保持顺序）
            List<String> distinctNames = new ArrayList<>(uniqueNames);
            // 截取前100个（防止超过需求）
            if (distinctNames.size() > 100) {
                distinctNames = distinctNames.subList(0, 100);
            }

            // 使用去重后的列表生成字符串
            String namesStr = String.join(",", distinctNames);

            Map<String, Object> insertParams = new HashMap<>();
            insertParams.put("namesStr", namesStr);
            insertParams.put("orderNo", order.getOrderNo());
            alipayNameOrderService.insertNamesByOrderNo(insertParams);

            // 使用已注入的alipayNameOrderService
            result.put("names", distinctNames); // 返回去重后的列表
            result.put("success", true);
            result.put("orderNo", orderNo);


        } catch (Exception e) {
            e.printStackTrace();
            result.put("error", "生成名字失败: " + e.getMessage());
        }

        return result; // 返回result而不是null
    }

}
